package com.fc.tms.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fc.framework.action.AbstractAction;
import com.fc.system.service.ExcelReader;
import com.fc.tms.constant.Course;
import com.fc.tms.constant.Team;
import com.fc.tms.constant.UserType;
import com.fc.tms.constant.editor.CourseEnumEditor;
import com.fc.tms.constant.editor.TeamEnumEditor;
import com.fc.tms.entity.User;
import com.fc.tms.filter.UserFilter;
import com.fc.tms.service.ExcelImportService;
import com.fc.tms.service.UserService;

@Controller
@RequestMapping("/user")
public class UserAction extends AbstractAction {

    private static final Logger logger = LoggerFactory.getLogger(UserAction.class);

    private static final String[] years = new String[] { "2013", "2014", "2015", "2016" };
    private static final String[] months = new String[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                                                         "11", "12" };

    @Resource
    UserService userService;

    @Resource
    ExcelImportService excelImportService;

    @Resource
    ExcelReader dimissionReader;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        binder.registerCustomEditor(Course.class, new CourseEnumEditor());
        binder.registerCustomEditor(Team.class, new TeamEnumEditor());
    }

    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request) {
        model.addAttribute("filter", new UserFilter());

        setDefaultDate(model, null, null);

        return Pages.USER_LIST;
    }

    private void setDefaultDate(Model model, String year, String month) {
        Date current = new Date();

        model.addAttribute("year", year == null ? new SimpleDateFormat("yyyy").format(current) : year);
        model.addAttribute("month", month == null ? new SimpleDateFormat("MM").format(current) : month);
        model.addAttribute("years", years);
        model.addAttribute("months", months);
    }

    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public String list(Model model, HttpServletRequest request, @ModelAttribute UserFilter filter,
                       @RequestParam String year, @RequestParam String month) throws ParseException {
        filter.setUserType(UserType.STUDENT);

        Integer yearInteger = Integer.valueOf(year);
        Integer monthInteger = Integer.valueOf(month.startsWith("0") ? month.substring(1) : month);

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(yearInteger, monthInteger - 1, 1, 0, 0, 0);
        startCalendar.set(Calendar.MILLISECOND, 0);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(yearInteger, monthInteger - 1, startCalendar.getMaximum(Calendar.DAY_OF_MONTH) - 1, 23, 59, 59);
        endCalendar.set(Calendar.MILLISECOND, 999);

        logger.info("start: " + startCalendar.getTime() + ", end: " + endCalendar.getTime());

        filter.setJobTransferBefore(endCalendar.getTime());
        filter.setJobTransferAfter(startCalendar.getTime());
        filter.setIsDimission(Boolean.FALSE);
        List<User> userList = userService.find(filter);
        model.addAttribute("userList", userList);

        model.addAttribute("filter", filter);

        setDefaultDate(model, year, month);

        return Pages.USER_LIST;
    }

    @RequestMapping(value = "/upload/{type}")
    public @ResponseBody
    OperationResult upload(@PathVariable String type, Model model, MultipartHttpServletRequest request) {
        List<MultipartFile> files = request.getFiles("file");//取得from里面的参数
        String uploadpath = request.getSession().getServletContext().getRealPath("upload");
        for (MultipartFile file : files) {
            if (file.isEmpty())
                continue;

            String fileName = uploadpath + "\\" + new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss").format(new Date())
                              + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            FileOutputStream fileOS = null;
            try {
                fileOS = new FileOutputStream(fileName);
                fileOS.write(file.getBytes());
                fileOS.close();

                logger.error("File: " + fileName);

                Map<Integer, String> msg = null;

                if ("transfer".equals(type)) {
                    msg = excelImportService.importTransferLog(fileName);
                } else if ("training".equals(type)) {
                    msg = excelImportService.importTrainingLog(fileName);
                } else {
                    msg = dimissionReader.read(fileName);
                }

                if (msg.isEmpty()) {
                    return this.success();
                } else {
                    String error = "";
                    for (Entry<Integer, String> e : msg.entrySet()) {
                        error = error + ";行号：" + e.getKey() + ",错误信息：" + e.getValue();
                    }
                    return this.failed(error.substring(1));
                }
            } catch (Exception e) {
                logger.error("Import error:" + e, e);
                return this.failed(e);
            } finally {
                if (fileOS != null) {
                    try {
                        fileOS.close();
                    } catch (IOException e) {
                        logger.error("Close error!", e);
                    }
                }
                File uploadFile = new File(fileName);
                if (uploadFile.exists()) {
                    boolean isDeleted = uploadFile.delete();
                    logger.info("File is deleted: " + isDeleted);
                }
            }
        }
        return this.success();
    }

    public static String[] getYears() {
        return years;
    }

    public static String[] getMonths() {
        return months;
    }
}